package team.umbc;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

import android.app.Application;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.util.Log;

public class PlaceApplication extends Application {
	PlacesDB placesDB;
	SQLiteDatabase db;
	// PlaceData placeData;

	FriendsDB friendsDB;
	Facebook facebook;

	@Override
	public void onCreate() {
		super.onCreate();

		facebook = new Facebook(CheckinActivity.APP_ID);
		SharedPreferences settings = getSharedPreferences(
				CheckinActivity.PREFS_NAME, 0);
		facebook.setAccessToken(settings.getString(
				CheckinActivity.ACCESS_TOKEN, ""));
	}

	public void onTerminate() {
		super.onTerminate();
		db.close();
	}

	public synchronized int fetchPlaces() {
		placesDB = new PlacesDB(getApplicationContext());
		db = placesDB.getWritableDatabase();

		ContentValues values = new ContentValues();
		String[] places = { "RAC", "Admin", "Sond", "ACIV", "Math/Psych" };
		String[] longitude = { "-76.712793", "-76.713485", "-76.712776",
				"-76.713141", "-76.712417" };
		String[] latitude = { "39.252665", "39.253059", "39.253475",
				"39.253633", "39.254102" };
		String[] fbID = { "185092618178693", "131233586923806", "DEFAULT Sond",
				"149152175116380", "DEFAULT M/P" };

		SQLiteStatement dbJournalCountQuery;
		dbJournalCountQuery = db.compileStatement("select count(*) from "
				+ PlacesDB.TABLE);
		long rows = dbJournalCountQuery.simpleQueryForLong();

		if (rows != places.length) {
			// id(already populated), name, tag, button, fbID, 4sID
			int tag = 100;
			for (int i = 0; i < places.length; i++) {
				values.clear();
				values.put(PlacesDB.P_NAME, places[i]);
				values.put(PlacesDB.P_TAG, tag + i);
				values.put(PlacesDB.P_LAT, latitude[i]);
				values.put(PlacesDB.P_LONG, longitude[i]);
				values.put(PlacesDB.P_BUTTON, "null");
				values.put(PlacesDB.P_FB_ID, fbID[i]);
				values.put(PlacesDB.P_4S_ID, "Default_4S ID_for_" + places[i]);
				db.insertOrThrow(PlacesDB.TABLE, null, values);
			}

		}
		placesDB.close();
		db.close();
		db = null;
		return 0;
	}

	public synchronized int fetchFriends() throws JSONException, FacebookError {
		AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
		Bundle bundle = new Bundle();
		bundle.putString("fields", "name, id");

		String response;
		JSONArray friendsData;
		JSONObject data;
		String id,  name;
		URL img;

		friendsDB = new FriendsDB(getApplicationContext());
		db = friendsDB.getWritableDatabase();
		
		db.delete(FriendsDB.TABLE, null, null);

		ContentValues values = new ContentValues();

		Bundle parameters = new Bundle();

		parameters.putString("format", "json");
		parameters.putString("access_token", facebook.getAccessToken());
 
		String url = "https://graph.facebook.com/me/friends";
		try {
			response = Util.openUrl(url, "GET", parameters);
			JSONObject obj = Util.parseJson(response);
			JSONArray array = obj.optJSONArray("data");

		if (array != null) {
			for (int i = 0; i < array.length(); i++) {

				id = array.getJSONObject(i).getString("id");
				name = array.getJSONObject(i).getString("name");
				img = new URL("https://graph.facebook.com​/" + id + "/picture");
				
				values.clear();
				values.put(FriendsDB.F_FB_ID, id);
				values.put(FriendsDB.F_IMAGE, img.toString());
				values.put(FriendsDB.F_NAME, name);
				
				db.insertOrThrow(FriendsDB.TABLE, null, values);
			}
		}
		} catch (MalformedURLException e) { 
			 e.printStackTrace(); 
		} catch (IOException e)  {
			 e.printStackTrace();
    	} finally {
			db.close();	
			friendsDB.close();
		}

			
			/*
			 * try { response = facebook.request("me/friends", bundle);
			 * System.out.println(response); data = Util.parseJson(response);
			 * friendsData = data.getJSONArray("data");
			 * 
			 * for (int i = 0; i < friendsData.length(); i++) { JSONObject
			 * friend = friendsData.getJSONObject(i); id =
			 * friend.getString("id"); //img =
			 * facebook.request("https://graph.facebook.com​/" + id +
			 * "/picture"); values.clear(); values.put(FriendsDB.F_NAME,
			 * friend.getString("name")); values.put(FriendsDB.F_FB_ID, id);
			 * //values.put(FriendsDB.F_IMAGE, img);
			 * db.insertOrThrow(PlacesDB.TABLE, null, values); }
			 * 
			 * } catch (MalformedURLException e) { // TODO Auto-generated catch
			 * block e.printStackTrace(); } catch (IOException e) { // TODO
			 * Auto-generated catch block e.printStackTrace(); } finally {
			 * 
			 * }
			 */

			return 0;
		}

		// public PlaceData getPlaceData() {
		// return placeData;
		// }
}
